﻿using System;
using System.ComponentModel;
using System.Linq;
using Inaction.Core;
using Inaction.Mapping;
using System.ComponentModel.DataAnnotations;

namespace Inaction.Business.Security
{
    [DisplayName("用户")]
    [Table("UserInfo")]
    [Serializable]
    public class UserInfo : Abstract.UserInfo<UserInfo>
    {
        #region 子表

        [Display(Description = "用户角色"), DisplayName("用户角色")]
        public UserRoleList UserRoles
        {
            get { return GetChild<UserRoleList, UserRole>(); }
        }

        public UserRoleVList UserRoleViews
        {
            get { return GetChild<UserRoleVList, UserRoleV>(); }
        }
        #endregion

        #region 方法
        protected override void OnPropertyChanged(IProperty property)
        {
            base.OnPropertyChanged(property);
            if (property == NumberProperty)
            {
                if (!string.IsNullOrEmpty(Number))
                {
                    Password = Inaction.Security.DEncrypt.MakeHashSalt(Number);
                }
                else
                {
                    Password = null;
                }
            }
        }
        public void RefreshUserRole(RoleInfo role)
        {
            var userRole = UserRoles.FirstOrDefault(p => p.RoleId == role.Id);
            if (userRole != null && !role.Selected)
            {
                UserRoles.Remove(userRole);
            }
            if (userRole == null && role.Selected)
            {
                userRole = UserRoles.AddNew();
                userRole.RoleId = role.Id;
            }
        }
        #endregion
    }

    [DisplayName("用户列表"), Serializable]
    public class UserInfoList : Inaction.Business.EntityList<UserInfoList, UserInfo>
    {
    }
}
